<?php

namespace App\Think;

class Redis
{
    public static $instance;
    private $redisPool;

    static function init()
    {
        if(!isset(self::$instance)) self::$instance = new static();
        return self::$instance;
    }

    // public function __construct($opt = []) {
    //     $this->redisPool = \EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
    // }

    public function __clone(){}

    public function get($key, $default = false){
        return $this->exec(['act'=>'get', 'key'=>$key, 'default'=>$default]);
    }
    public function set($key, $value, $expire = null){
        return $this->exec(['act'=>'set', 'key'=>$key, 'value'=>$value, 'expire'=>$expire]);
    }
    public function del($key){
        return $this->exec(['act'=>'del', 'key'=>$key]);
    }

    public function sAdd($key, $value){
        return $this->exec(['act'=>'sAdd', 'key'=>$key, 'value'=>$value]);
    }
    public function sMembers($key){
        return $this->exec(['act'=>'sMembers', 'key'=>$key]);
    }
    public function sRem($key, $value){
        return $this->exec(['act'=>'sRem', 'key'=>$key, 'value'=>$value]);
    }

    public function exec($param){
        $redisPool = \EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
        $res = "";
        switch ($param['act']) {
            case 'set':
                $res = $redisPool->set($param['key'], $param['value'], $param['expire']);
                break;
            case 'get':
                $res = $redisPool->get($param['key']);
                if(!$res) $res = $param['default'];
                break;
            case 'del':
                $res = $redisPool->del($param['key']);
                break;
            case 'sAdd':
                $res = $redisPool->sAdd($param['key'], $param['value']);
                break;
            case 'sMembers':
                $res = $redisPool->sMembers($param['key']);
                break;
            case 'sRem':
                $res = $redisPool->sRem($param['key'], $param['value']);
                break;
            default:
                break;
        }
        \EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redisPool);
        return $res;
    }


}
